package org.lqq;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by 李清泉 on 2017/12/12.
 *
 * @remark
 */
public class HttpClientUtils {
    /**
     * 发送Post请求，可以传多个参数
     *
     * @param urlPath
     * @param
     * @return
     * @throws Exception
     */
    public static String postData(String urlPath, String content) throws Exception {
        String result = "";
        HttpURLConnection httpConn = null;
        try {
            // 建立连接
            URL url = new URL(urlPath);
            httpConn = (HttpURLConnection) url.openConnection();
            // 设置参数
            httpConn.setDoOutput(true); // 需要输出
            httpConn.setDoInput(true); // 需要输入
            httpConn.setUseCaches(false); // 不允许缓存
            httpConn.setRequestMethod("POST"); // 设置POST方式连接
            // 设置请求属性
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            httpConn.setRequestProperty("Charset", "UTF-8");
            // 连接,也可以不用明文connect，使用下面的httpConn.getOutputStream()会自动connect
            httpConn.connect();
            // 建立输入流，向指向的URL传入参数
            DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
            dos.writeBytes(content);
            dos.flush();
            dos.close();
            // 获得响应状态
            int resultCode = httpConn.getResponseCode();

            if (HttpURLConnection.HTTP_OK == resultCode) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                InputStream inputStream = httpConn.getInputStream();
                byte[] buff = new byte[128];
                int k;
                while ((k = inputStream.read(buff, 0, buff.length)) > 0) {
                    outputStream.write(buff, 0, k);
                }
                result = new String(outputStream.toByteArray(), "utf-8");
            }
        } finally {
            if (httpConn != null) {
                httpConn.disconnect();
            }
        }
        return result;
    }
}
